import { Button, Result, Card, List } from 'antd';
import PageHeader from '@/components/page/PageHeader';
import { useMemo } from 'react';
import { history, useModel } from 'umi';
import IconFont from '@/components/base/IconFont';
import _ from 'lodash';

export default () => {
  const { menuDatas } = useModel('sysInfo', (ret) => ({
    menuDatas: ret.sysInfo?.menuDatas,
  }));
  const lists = useMemo(() => {
    const rpath = history.location.pathname;
    const menuData = _.isEmpty(menuDatas) ? undefined : menuDatas!.find((m) => m.path === rpath);
    if (!menuData) {
      return null;
    }
    if (_.isEmpty(menuData.routes)) {
      return null;
    }
    const buildList = (m: API.MenuData) => {
      const mlist: API.MenuData[] = [];
      m.routes!.forEach((r) => {
        if (_.isEmpty(r.routes)) {
          mlist.push(r);
        }
      });
      return (
        <Card
          title={
            <>
              <IconFont type={m.icon!} />
              {m.name}
            </>
          }
          bodyStyle={{ height: 350, overflow: 'auto' }}
          style={{ width: 238 }}
        >
          {mlist!.map((i) => {
            return (
              <p key={i.id}>
                <a href={'/#' + i.path} style={{ color: 'rgb(0 0 0 / 85%)' }}>
                  <IconFont type={i.icon!} />
                  {i.name}
                </a>
              </p>
            );
          })}
        </Card>
      );
    };
    const mlist: API.MenuData[] = [];
    let hasTwoLev = false;
    menuData.routes!.forEach((cm) => {
      if (!_.isEmpty(cm.routes)) {
        mlist.push(cm);
      } else {
        hasTwoLev = true;
      }
    });
    const cardList: JSX.Element[] = [];
    if (hasTwoLev) {
      cardList.push(buildList(menuData));
    }
    if (!_.isEmpty(mlist)) {
      mlist.forEach((m) => {
        cardList.push(buildList(m));
      });
    }
    return cardList;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [history.location.pathname, menuDatas]);
  return (
    <PageHeader>
      {lists !== null ? (
        <List
          grid={{
            gutter: 16,
            xl: 2,
          }}
          bordered={false}
          size="small"
          dataSource={lists}
          renderItem={(item) => <List.Item>{item}</List.Item>}
        />
      ) : (
        <Result
          status="404"
          title="404"
          subTitle="对不起, 你访问的页面不存在."
          extra={
            <Button type="primary" onClick={() => history.push('/')}>
              Back Home
            </Button>
          }
        />
      )}
    </PageHeader>
  );
};
